using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

public partial class MainForm : Form
{
    private UpdateManager updateManager;
    private SimpleHttpServer httpServer;
    private ListView productListView;
    private ComboBox versionComboBox;
    private TextBox logTextBox;
    private Button updateButton;
    private Button rollbackButton;
    private Button refreshButton;
    private ProgressBar progressBar;
    private Label statusLabel;
    private Label selectedProductLabel;
    private NotifyIcon notifyIcon;
    private bool isTaskRunning = false;

    public MainForm()
    {
        try
        {
            Application.ThreadException += Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            
            updateManager = new UpdateManager();
            httpServer = new SimpleHttpServer(updateManager, 8080);
            httpServer.Start();
            InitializeComponent();
            InitializeNotifyIcon();
            
            if (!IsRunningAsAdministrator())
            {
                LogMessage("警告: 当前程序未以管理员权限运行，IIS相关功能可能无法正常使用。", Color.Orange);
            }
            
            updateManager.LoadProductsFromDatabase();
            LoadProducts();
        }
        catch (Exception ex)
        {
            Logger.LogError("MainForm初始化失败", ex);
            MessageBox.Show($"程序初始化失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            throw;
        }
    }
    
    private void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
        Logger.LogError("线程异常", e.Exception);
        MessageBox.Show($"程序异常: {e.Exception.Message}\n\n请查看logs文件夹中的错误日志", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    
    private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        if (e.ExceptionObject is Exception ex)
        {
            Logger.LogError("未处理异常", ex);
            MessageBox.Show($"程序崩溃: {ex.Message}\n\n请查看logs文件夹中的错误日志", "严重错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
    
    private bool IsRunningAsAdministrator()
    {
        try
        {
            var identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            var principal = new System.Security.Principal.WindowsPrincipal(identity);
            return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
        }
        catch
        {
            return false;
        }
    }
    
    private bool IsIISInstalled()
    {
        try
        {
            // 检查IIS服务是否存在
            using (var sc = new System.ServiceProcess.ServiceController("W3SVC"))
            {
                var status = sc.Status;
                return true;
            }
        }
        catch (System.InvalidOperationException)
        {
            // 服务不存在
            return false;
        }
        catch (Exception ex)
        {
            Logger.LogError("检测IIS服务安装状态失败", ex);
            return false;
        }
    }
    
    private void RestartAsAdmin()
    {
        try
        {
            var processInfo = new System.Diagnostics.ProcessStartInfo
            {
                FileName = Application.ExecutablePath,
                UseShellExecute = true,
                Verb = "runas"
            };
            
            System.Diagnostics.Process.Start(processInfo);
            Environment.Exit(0);
        }
        catch (Exception ex)
        {
            Logger.LogError("以管理员身份重启失败", ex);
            MessageBox.Show($"以管理员身份重启失败：{ex.Message}\n\n请手动右键点击程序，选择'以管理员身份运行'。", "重启失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
    
    private async Task<bool> InstallIISAsync()
    {
        try
        {
            LogMessage("正在自动安装IIS服务...", Color.Blue);
            SetUIEnabled(false);
            progressBar.Style = ProgressBarStyle.Blocks;
            progressBar.Value = 0;
            progressBar.Maximum = 100;
            progressBar.Visible = true;
            statusLabel.Text = "正在准备安装IIS服务...";
            
            Application.DoEvents();
            
            // 改进的进度更新
            var progressTimer = new System.Windows.Forms.Timer { Interval = 1000 };
            int currentProgress = 0;
            bool processCompleted = false;
            progressTimer.Tick += (s, e) =>
            {
                if (!processCompleted && currentProgress < 85)
                {
                    currentProgress += 3;
                    progressBar.Value = currentProgress;
                    
                    // 根据进度显示不同的状态信息
                    if (currentProgress <= 15)
                        statusLabel.Text = "正在检查系统兼容性...";
                    else if (currentProgress <= 35)
                        statusLabel.Text = "正在下载IIS组件...";
                    else if (currentProgress <= 60)
                        statusLabel.Text = "正在安装IIS核心功能...";
                    else if (currentProgress <= 85)
                        statusLabel.Text = "正在配置IIS服务...";
                    
                    Application.DoEvents();
                }
                else if (!processCompleted)
                {
                    // 在85%后缓慢增长，等待进程完成
                    statusLabel.Text = "正在完成IIS配置，请耐心等待...";
                    Application.DoEvents();
                }
            };
            progressTimer.Start();
            
            // 使用DISM命令安装IIS（更稳定）
            var dismFeatures = "IIS-WebServerRole IIS-WebServer IIS-CommonHttpFeatures IIS-HttpErrors IIS-StaticContent IIS-DefaultDocument IIS-DirectoryBrowsing IIS-ASPNET45 IIS-NetFxExtensibility45 IIS-ISAPIExtensions IIS-ISAPIFilter IIS-HttpLogging IIS-RequestFiltering IIS-BasicAuthentication IIS-WindowsAuthentication IIS-ManagementConsole";
            var dismCommand = $"dism /online /enable-feature /featurename:{dismFeatures.Replace(" ", " /featurename:")} /all /norestart";
            
            var process = new System.Diagnostics.Process
            {
                StartInfo = new System.Diagnostics.ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    Arguments = $"/c {dismCommand}",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                }
            };
            
            LogMessage("正在执行DISM命令...", Color.Blue);
            LogMessage($"命令: {dismCommand}", Color.Gray);
            process.Start();
            
            // 异步读取输出
            var outputTask = Task.Run(() =>
            {
                var output = new System.Text.StringBuilder();
                string line;
                while ((line = process.StandardOutput.ReadLine()) != null)
                {
                    output.AppendLine(line);
                    Invoke(() => LogMessage($"[DISM] {line}", Color.Gray));
                }
                return output.ToString();
            });
            
            var errorTask = Task.Run(() => process.StandardError.ReadToEnd());
            
            // 等待进程完成，设置超时
            var processTask = Task.Run(() => process.WaitForExit());
            var timeoutTask = Task.Delay(TimeSpan.FromMinutes(10)); // 10分钟超时
            
            var completedTask = await Task.WhenAny(processTask, timeoutTask);
            
            processCompleted = true;
            progressTimer.Stop();
            
            if (completedTask == timeoutTask)
            {
                LogMessage("IIS安装超时，正在终止进程...", Color.Orange);
                try
                {
                    if (!process.HasExited)
                    {
                        process.Kill();
                        process.WaitForExit(5000);
                    }
                }
                catch { }
                
                progressBar.Value = 50;
                statusLabel.Text = "安装超时";
                MessageBox.Show("IIS安装超时。\n\n可能原因：\n1. 网络连接问题\n2. 系统资源不足\n3. Windows更新服务异常\n\n请检查网络连接和系统状态后重试。", "安装超时", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            
            progressBar.Value = 95;
            statusLabel.Text = "正在完成安装...";
            Application.DoEvents();
            
            var output = await outputTask;
            var error = await errorTask;
            
            if (process.ExitCode == 0)
            {
                LogMessage("IIS安装命令执行成功", Color.Green);
                progressBar.Value = 98;
                statusLabel.Text = "正在验证安装结果...";
                LogMessage("请稍候，正在验证安装结果...", Color.Blue);
                
                Application.DoEvents();
                
                // 等待系统完成安装，显示进度
                for (int i = 0; i < 30; i++)
                {
                    await Task.Delay(200);
                    Application.DoEvents();
                }
                
                progressBar.Value = 100;
                statusLabel.Text = "验证安装结果...";
                
                // 再次检查IIS是否安装成功
                if (IsIISInstalled())
                {
                    LogMessage("IIS安装成功！", Color.Green);
                    MessageBox.Show("IIS安装成功！\n\n现在可以继续部署Web应用程序。", "安装成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return true;
                }
                else
                {
                    LogMessage("警告: IIS安装可能需要重启系统才能生效", Color.Orange);
                    MessageBox.Show("IIS安装完成，但可能需要重启系统才能生效。\n\n请重启后再试。", "需要重启", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }
            }
            else
            {
                LogMessage($"DISM命令执行失败，退出代码: {process.ExitCode}", Color.Red);
                LogMessage($"错误输出: {error}", Color.Red);
                LogMessage($"标准输出: {output}", Color.Gray);
                
                var errorMsg = $"DISM命令执行失败\n\n" +
                              $"退出代码: {process.ExitCode}\n" +
                              $"错误信息: {error}\n\n" +
                              $"可能的原因：\n" +
                              $"1. 程序未以管理员身份运行\n" +
                              $"2. Windows版本不支持该功能\n" +
                              $"3. 系统文件损坏或缺失\n\n" +
                              $"请手动安装IIS或检查系统状态。";
                              
                MessageBox.Show(errorMsg, "安装失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        catch (Exception ex)
        {
            Logger.LogError("自动安装IIS失败", ex);
            LogMessage($"IIS安装失败: {ex.Message}", Color.Red);
            MessageBox.Show($"IIS安装失败：\n\n{ex.Message}\n\n请手动安装IIS或以管理员身份运行程序。", "安装失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return false;
        }
        finally
        {
            progressBar.Visible = false;
            progressBar.Value = 0;
            statusLabel.Text = "就绪";
            SetUIEnabled(true);
        }
    }

    private void InitializeComponent()
    {
        Text = "产品自动更新系统";
        Size = new Size(1040, 780);
        MinimumSize = new Size(1040, 780);
        StartPosition = FormStartPosition.CenterScreen;
        AutoScaleMode = AutoScaleMode.Font;

        var mainLayout = new TableLayoutPanel
        {
            Dock = DockStyle.Fill,
            ColumnCount = 1,
            RowCount = 7,
            Padding = new Padding(10)
        };
        mainLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 30F));
        mainLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 40F));
        mainLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 30F));
        mainLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 100F));
        mainLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 30F));
        mainLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 30F));
        mainLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 30F));

        // 产品列表标签
        var productLabel = new Label { Text = "产品列表:", Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleLeft };
        mainLayout.Controls.Add(productLabel, 0, 0);

        // 产品列表
        productListView = new ListView
        {
            Dock = DockStyle.Fill,
            View = View.Details,
            FullRowSelect = true,
            GridLines = true,
            MultiSelect = true,
            CheckBoxes = true
        };
        productListView.Columns.Add("应用名称", 120);
        productListView.Columns.Add("类型", 60);
        productListView.Columns.Add("所属产品", 100);
        productListView.Columns.Add("当前版本", 80);
        productListView.Columns.Add("路径", 260);
        productListView.Columns.Add("状态", 80);
        productListView.ItemSelectionChanged += ProductListView_ItemSelectionChanged;
        mainLayout.Controls.Add(productListView, 0, 1);

        // 选中产品显示
        selectedProductLabel = new Label { Text = "请选择产品", Dock = DockStyle.Fill, ForeColor = Color.Blue, TextAlign = ContentAlignment.MiddleLeft };
        mainLayout.Controls.Add(selectedProductLabel, 0, 2);

        // 操作按钮区域
        var buttonPanel = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 10, RowCount = 2 };
        for (int i = 0; i < 10; i++) buttonPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 10F));
        buttonPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 50F));
        buttonPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 50F));

        var editProductButton = new Button { Text = "修改产品", Dock = DockStyle.Fill, Margin = new Padding(2) };
        editProductButton.Click += EditProductButton_Click;
        buttonPanel.Controls.Add(editProductButton, 0, 0);

        var deleteProductButton = new Button { Text = "删除选中", Dock = DockStyle.Fill, Margin = new Padding(2) };
        deleteProductButton.Click += DeleteProductButton_Click;
        buttonPanel.Controls.Add(deleteProductButton, 1, 0);

        var deployServiceButton = new Button { Text = "部署服务", Dock = DockStyle.Fill, Margin = new Padding(2) };
        deployServiceButton.Click += DeployServiceButton_Click;
        buttonPanel.Controls.Add(deployServiceButton, 2, 0);

        var deployIISButton = new Button { Text = "部署IIS", Dock = DockStyle.Fill, Margin = new Padding(2) };
        deployIISButton.Click += DeployIISButton_Click;
        buttonPanel.Controls.Add(deployIISButton, 3, 0);

        var versionLabel = new Label { Text = "版本选择:", Anchor = AnchorStyles.Left, TextAlign = ContentAlignment.MiddleLeft };
        buttonPanel.Controls.Add(versionLabel, 0, 1);

        versionComboBox = new ComboBox {  Anchor = AnchorStyles.Left, DropDownStyle = ComboBoxStyle.DropDownList, Margin = new Padding(2) };
        buttonPanel.Controls.Add(versionComboBox, 1, 1);

        updateButton = new Button { Text = "批量更新", Dock = DockStyle.Fill, Margin = new Padding(2) };
        updateButton.Click += BatchUpdateButton_Click;
        buttonPanel.Controls.Add(updateButton, 2, 1);

        var singleUpdateButton = new Button { Text = "单个更新", Dock = DockStyle.Fill, Margin = new Padding(2) };
        singleUpdateButton.Click += SingleUpdateButton_Click;
        buttonPanel.Controls.Add(singleUpdateButton, 3, 1);

        var checkUpdateButton = new Button { Text = "检测更新", Dock = DockStyle.Fill, Margin = new Padding(2) };
        checkUpdateButton.Click += CheckUpdateButton_Click;
        buttonPanel.Controls.Add(checkUpdateButton, 4, 1);

        refreshButton = new Button { Text = "刷新", Dock = DockStyle.Fill, Margin = new Padding(2) };
        refreshButton.Click += (s, e) => LoadProducts();
        buttonPanel.Controls.Add(refreshButton, 5, 1);

        var viewIISButton = new Button { Text = "查看IIS", Dock = DockStyle.Fill, Margin = new Padding(2) };
        viewIISButton.Click += ViewIISButton_Click;
        buttonPanel.Controls.Add(viewIISButton, 6, 1);

        var syncToServerButton = new Button { Text = "同步", Dock = DockStyle.Fill, Margin = new Padding(2) };
        syncToServerButton.Click += SyncToServerButton_Click;
        buttonPanel.Controls.Add(syncToServerButton, 7, 1);

        mainLayout.Controls.Add(buttonPanel, 0, 3);

        // 进度条
        progressBar = new ProgressBar { Dock = DockStyle.Fill, Style = ProgressBarStyle.Marquee, Visible = false };
        mainLayout.Controls.Add(progressBar, 0, 4);

        // 状态标签
        statusLabel = new Label { Text = "就绪", Dock = DockStyle.Fill, ForeColor = Color.Blue, TextAlign = ContentAlignment.MiddleLeft };
        mainLayout.Controls.Add(statusLabel, 0, 5);

        // 日志区域
        logTextBox = new TextBox
        {
            Dock = DockStyle.Fill,
            Multiline = true,
            ScrollBars = ScrollBars.Vertical,
            ReadOnly = true,
            BackColor = Color.Black,
            ForeColor = Color.Lime,
            Font = new Font("Consolas", 9)
        };
        mainLayout.Controls.Add(logTextBox, 0, 6);

        Controls.Add(mainLayout);
        FormClosing += MainForm_FormClosing;
    }
    
    private void InitializeNotifyIcon()
    {
        notifyIcon = new NotifyIcon
        {
            Icon = SystemIcons.Application,
            Text = "产品自动更新系统",
            Visible = true
        };
        
        var contextMenu = new ContextMenuStrip();
        contextMenu.Items.Add("显示", null, (s, e) => { Show(); WindowState = FormWindowState.Normal; });
        contextMenu.Items.Add("退出", null, (s, e) => { notifyIcon.Visible = false; Environment.Exit(0); });
        notifyIcon.ContextMenuStrip = contextMenu;
        
        notifyIcon.DoubleClick += (s, e) => { Show(); WindowState = FormWindowState.Normal; };
    }
    
    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (isTaskRunning)
        {
            MessageBox.Show("当前有任务正在进行，无法关闭程序", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            e.Cancel = true;
            return;
        }
        
        e.Cancel = true;
        Hide();
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            httpServer?.Stop();
        }
        base.Dispose(disposing);
    }

    private void LoadProducts()
    {
        productListView.Items.Clear();
        var products = updateManager.GetProducts();

        foreach (var product in products)
        {
            var item = new ListViewItem(product.Name);
            item.SubItems.Add(product.Type.ToUpper());
            item.SubItems.Add(product.ProductName);
            item.SubItems.Add(product.CurrentVersion);
            item.SubItems.Add(product.Path);
            item.SubItems.Add("运行中");
            item.Tag = product;
            productListView.Items.Add(item);
        }

        LogMessage($"已加载 {products.Count} 个产品");
    }

    private async void BatchUpdateButton_Click(object sender, EventArgs e)
    {
        var checkedProducts = GetCheckedProducts();
        if (checkedProducts.Count == 0)
        {
            MessageBox.Show("请勾选要更新的产品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }

        var version = versionComboBox.Text.Trim();
        if (string.IsNullOrEmpty(version))
        {
            MessageBox.Show("请选择目标版本", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }

        var result = MessageBox.Show($"确定要将 {checkedProducts.Count} 个产品更新到版本 {version} 吗？", "确认批量更新", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (result != DialogResult.Yes)
            return;

        await BatchUpdateProducts(checkedProducts, version);
    }

    private List<Product> GetCheckedProducts()
    {
        var checkedProducts = new List<Product>();
        foreach (ListViewItem item in productListView.CheckedItems)
        {
            checkedProducts.Add((Product)item.Tag);
        }
        return checkedProducts;
    }

    private async Task BatchUpdateProducts(List<Product> products, string targetVersion)
    {
        SetUIEnabled(false);
        progressBar.Visible = true;
        progressBar.Style = ProgressBarStyle.Blocks;
        progressBar.Maximum = products.Count;
        progressBar.Value = 0;

        int successCount = 0;
        int failCount = 0;

        LogMessage($"开始批量更新 {products.Count} 个产品到版本 {targetVersion}", Color.Blue);

        for (int i = 0; i < products.Count; i++)
        {
            var product = products[i];
            progressBar.Value = i;
            statusLabel.Text = $"正在更新 {product.Name} ({i + 1}/{products.Count})...";
            
            try
            {
                LogMessage($"[{product.Name}] 开始更新从 {product.CurrentVersion ?? "未知"} 到 {targetVersion}");
                
                var progress = new Progress<string>(message =>
                {
                    LogMessage($"[{product.Name}] {message}");
                    Application.DoEvents();
                });

                bool success = await updateManager.UpdateProduct(product.Id, targetVersion, progress);

                if (success)
                {
                    LogMessage($"[{product.Name}] 更新成功", Color.Green);
                    await updateManager.GenerateAppConfig(product, targetVersion);
                    
                    // 更新列表中的版本显示
                    var listItem = productListView.Items.Cast<ListViewItem>().FirstOrDefault(item => ((Product)item.Tag).Id == product.Id);
                    if (listItem != null)
                    {
                        listItem.SubItems[3].Text = targetVersion;
                    }
                    
                    successCount++;
                }
                else
                {
                    LogMessage($"[{product.Name}] 更新失败", Color.Red);
                    failCount++;
                }
            }
            catch (Exception ex)
            {
                LogMessage($"[{product.Name}] 更新异常: {ex.Message}", Color.Red);
                failCount++;
            }

            Application.DoEvents();
        }

        progressBar.Value = products.Count;
        statusLabel.Text = "批量更新完成";
        
        LogMessage($"批量更新完成：成功 {successCount} 个，失败 {failCount} 个", successCount > 0 ? Color.Green : Color.Red);
        MessageBox.Show($"批量更新完成！\n\n成功: {successCount} 个\n失败: {failCount} 个", "批量更新结果", MessageBoxButtons.OK, MessageBoxIcon.Information);

        LoadProducts();
        progressBar.Visible = false;
        statusLabel.Text = "就绪";
        SetUIEnabled(true);
    }

    private async Task<string> GetLatestVersionForProduct(Product product)
    {
        try
        {
            if (string.IsNullOrEmpty(product.ProductName))
                return "";
                
            var versions = await updateManager.GetVersionsFromAPI(product.ProductName);
            return versions.Count > 0 ? versions[0] : "";
        }
        catch
        {
            return "";
        }
    }

    private async void SingleUpdateButton_Click(object sender, EventArgs e)
    {
        var selectedProduct = GetSelectedProduct();
        if (selectedProduct == null)
        {
            MessageBox.Show("请选择要更新的产品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }

        var version = versionComboBox.Text.Trim();
        if (string.IsNullOrEmpty(version))
        {
            MessageBox.Show("请选择目标版本", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }

        await ProcessProduct(selectedProduct, version);
    }
    
    private bool IsVersionEqual(string version1, string version2)
    {
        if (string.IsNullOrEmpty(version1) || string.IsNullOrEmpty(version2))
            return false;
            
        // 移除版本号中的空格和特殊字符
        version1 = version1.Trim().Replace(" ", "").Replace("-", "").Replace("_", "");
        version2 = version2.Trim().Replace(" ", "").Replace("-", "").Replace("_", "");
        
        return string.Equals(version1, version2, StringComparison.OrdinalIgnoreCase);
    }
    
    private async Task<string> GetActualDeployedVersion(Product product)
    {
        try
        {
            if (product.Type.ToLower() == "iis")
            {
                // 检查IIS站点的实际版本
                return await GetIISDeployedVersion(product);
            }
            else if (product.Type.ToLower() == "service")
            {
                // 检查Windows服务的实际版本
                return await GetServiceDeployedVersion(product);
            }
            
            return "";
        }
        catch
        {
            return "";
        }
    }
    
    private async Task<string> GetIISDeployedVersion(Product product)
    {
        try
        {
            if (string.IsNullOrEmpty(product.Path) || !Directory.Exists(product.Path))
                return "";
                
            // 检查部署目录中的版本文件
            var versionFile = Path.Combine(product.Path, "version.txt");
            if (File.Exists(versionFile))
            {
                var content = await File.ReadAllTextAsync(versionFile);
                return content.Trim();
            }
            
            // 检查web.config中的版本信息
            var webConfig = Path.Combine(product.Path, "web.config");
            if (File.Exists(webConfig))
            {
                var content = await File.ReadAllTextAsync(webConfig);
                var versionMatch = System.Text.RegularExpressions.Regex.Match(content, @"version[""']?\s*[:=]\s*[""']?([^""'\s<>]+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                if (versionMatch.Success)
                {
                    return versionMatch.Groups[1].Value.Trim();
                }
            }
            
            return "";
        }
        catch
        {
            return "";
        }
    }
    
    private async Task<string> GetServiceDeployedVersion(Product product)
    {
        try
        {
            if (string.IsNullOrEmpty(product.Path) || !Directory.Exists(product.Path))
                return "";
                
            // 检查服务目录中的版本文件
            var versionFile = Path.Combine(product.Path, "version.txt");
            if (File.Exists(versionFile))
            {
                var content = await File.ReadAllTextAsync(versionFile);
                return content.Trim();
            }
            
            // 检查主执行文件的版本
            var exeFiles = Directory.GetFiles(product.Path, "*.exe");
            if (exeFiles.Length > 0)
            {
                var fileInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(exeFiles[0]);
                if (!string.IsNullOrEmpty(fileInfo.FileVersion))
                {
                    return fileInfo.FileVersion;
                }
            }
            
            return "";
        }
        catch
        {
            return "";
        }
    }



    private Product? GetSelectedProduct()
    {
        return productListView.SelectedItems.Count > 0 
            ? (Product)productListView.SelectedItems[0].Tag 
            : null;
    }

    private void ProductListView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
    {
        if (e.IsSelected)
        {
            var product = (Product)e.Item.Tag;
            selectedProductLabel.Text = $"已选择: {product.Name} - 当前版本: {product.CurrentVersion}";
            LoadAvailableVersions(product.Id);
        }
        else if (productListView.SelectedItems.Count == 0)
        {
            selectedProductLabel.Text = "请选择产品";
            versionComboBox.Items.Clear();
        }
    }

    private async void LoadAvailableVersions(string productId)
    {
        try
        {
            versionComboBox.Items.Clear();
            versionComboBox.Items.Add("正在加载...");
            versionComboBox.SelectedIndex = 0;
            versionComboBox.Enabled = false;
            
            var product = updateManager.GetProducts().FirstOrDefault(p => p.Id == productId);
            if (product != null && !string.IsNullOrEmpty(product.ProductName))
            {
                LogMessage($"正在加载产品 {product.ProductName} 的版本列表...", Color.Blue);
                
                var versions = await updateManager.GetVersionsFromAPI(product.ProductName);
                
                versionComboBox.Items.Clear();
                
                if (versions != null && versions.Count > 0)
                {
                    foreach (var version in versions)
                    {
                        versionComboBox.Items.Add(version);
                    }
                    versionComboBox.SelectedIndex = 0;
                    LogMessage($"已加载 {versions.Count} 个版本", Color.Green);
                }
                else
                {
                    versionComboBox.Items.Add("无可用版本");
                    versionComboBox.SelectedIndex = 0;
                    LogMessage($"产品 {product.ProductName} 没有可用版本", Color.Orange);
                }
            }
            else
            {
                versionComboBox.Items.Clear();
                versionComboBox.Items.Add("请设置产品名称");
                versionComboBox.SelectedIndex = 0;
                LogMessage("产品未设置 ProductName，无法加载版本", Color.Orange);
            }
        }
        catch (Exception ex)
        {
            Logger.LogError("加载版本列表失败", ex);
            LogMessage($"加载版本列表失败: {ex.Message}", Color.Red);
            
            versionComboBox.Items.Clear();
            versionComboBox.Items.Add("加载失败");
            versionComboBox.SelectedIndex = 0;
        }
        finally
        {
            versionComboBox.Enabled = true;
        }
    }





    private async Task ProcessProduct(Product product, string version)
    {
        SetUIEnabled(false);
        progressBar.Visible = true;

        var downloadUrl = await updateManager.GetVersionDownloadUrl(product.ProductName, version);
        LogMessage($"开始更新 {product.Name} 到版本 {version}");
        LogMessage($"下载地址: {downloadUrl}");
        statusLabel.Text = $"正在更新 {product.Name}...";
        
        var progress = new Progress<string>(message =>
        {
            LogMessage($"[{product.Name}] {message}");
        });

        bool success = await updateManager.UpdateProduct(product.Id, version, progress);

        if (success)
        {
            LogMessage($"[{product.Name}] 更新成功", Color.Green);
            await updateManager.GenerateAppConfig(product, version);
        }
        else
            LogMessage($"[{product.Name}] 更新失败", Color.Red);

        LoadProducts();
        progressBar.Visible = false;
        statusLabel.Text = "操作完成";
        SetUIEnabled(true);
    }

    private void SetUIEnabled(bool enabled)
    {
        updateButton.Enabled = enabled;
        refreshButton.Enabled = enabled;
        productListView.Enabled = enabled;
        versionComboBox.Enabled = enabled;
        isTaskRunning = !enabled;
    }

    private void LogMessage(string message, Color? color = null)
    {
        if (InvokeRequired)
        {
            Invoke(() => LogMessage(message, color));
            return;
        }

        var timestamp = DateTime.Now.ToString("HH:mm:ss");
        var logEntry = $"[{timestamp}] {message}\r\n";
        
        logTextBox.SelectionStart = logTextBox.TextLength;
        logTextBox.SelectionLength = 0;
       // logTextBox.SelectionColor = color ?? Color.Lime;
        logTextBox.AppendText(logEntry);
        logTextBox.ScrollToCaret();
    }



    private async void ViewIISButton_Click(object sender, EventArgs e)
    {
        SetUIEnabled(false);
        progressBar.Visible = true;
        statusLabel.Text = "正在采集IIS服务信息...";
        
        var progress = new Progress<string>(message => LogMessage($"[IIS采集] {message}"));
        
        try
        {
            var services = await updateManager.CollectIISServices(progress);
            LogMessage($"IIS服务采集完成，共采集到 {services.Count} 个站点", Color.Green);
            ShowIISServicesDialog(services);
        }
        catch (UnauthorizedAccessException ex)
        {
            Logger.LogError("IIS服务采集权限错误", ex);
            LogMessage($"权限错误: {ex.Message}", Color.Red);
            MessageBox.Show($"权限错误: {ex.Message}\n\n请右键点击程序，选择“以管理员身份运行”。", "权限不足", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        catch (Exception ex)
        {
            Logger.LogError("IIS服务采集失败", ex);
            LogMessage($"IIS服务采集失败: {ex.Message}", Color.Red);
        }
        
        progressBar.Visible = false;
        statusLabel.Text = "采集完成";
        SetUIEnabled(true);
    }

    private void ShowIISServicesDialog(List<IISServiceInfo> services)
    {
        var dialog = new Form
        {
            Text = "IIS服务列表",
            Size = new Size(900, 600),
            StartPosition = FormStartPosition.CenterParent,
            FormBorderStyle = FormBorderStyle.Sizable
        };

        var listView = new ListView
        {
            Location = new Point(10, 10),
            Size = new Size(860, 480),
            View = View.Details,
            FullRowSelect = true,
            GridLines = true
        };
        listView.Columns.Add("站点名称", 120);
        listView.Columns.Add("状态", 60);
        listView.Columns.Add("所属产品", 100);
        listView.Columns.Add("物理路径", 150);
        listView.Columns.Add("绑定", 120);
        listView.Columns.Add("应用程序池", 80);
        listView.Columns.Add("版本号", 80);
        listView.Columns.Add("采集时间", 100);

        foreach (var service in services)
        {
            var item = new ListViewItem(service.SiteName);
            item.SubItems.Add(service.State);
            item.SubItems.Add(service.ProductName);
            item.SubItems.Add(service.PhysicalPath ?? "");
            item.SubItems.Add(service.Bindings ?? "");
            item.SubItems.Add(service.ApplicationPool ?? "");
            item.SubItems.Add(service.CurrentVersion);
            item.SubItems.Add(service.CollectedTime.ToString("yyyy-MM-dd HH:mm:ss"));
            listView.Items.Add(item);
        }

        var closeButton = new Button
        {
            Text = "关闭",
            Location = new Point(800, 510),
            Size = new Size(70, 30),
            DialogResult = DialogResult.OK
        };

        listView.CheckBoxes = true;
        
        var addToProductsButton = new Button
        {
            Text = "添加到产品列表",
            Location = new Point(620, 510),
            Size = new Size(120, 30)
        };
        addToProductsButton.Click += (s, e) =>
        {
            if (listView.CheckedItems.Count == 0)
            {
                MessageBox.Show("请选择要添加的服务", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            
            foreach (ListViewItem item in listView.CheckedItems)
            {
                var service = services[item.Index];
                var product = new Product
                {
                    Id = $"iis_{service.SiteId}",
                    Name = service.SiteName,
                    Type = "iis",
                    Path = service.PhysicalPath ?? "",
                    SiteName = service.SiteName,
                    BackupPath = $"C:\\Backups\\{service.SiteName}",
                    CurrentVersion = service.CurrentVersion,
                    ProductName = service.ProductName
                };
                updateManager.AddProduct(product);
            }
            LoadProducts();
            MessageBox.Show($"已添加 {listView.CheckedItems.Count} 个服务到产品列表", "添加成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            dialog.Close();
        };
        
        dialog.Controls.Add(listView);
        dialog.Controls.Add(addToProductsButton);
        dialog.Controls.Add(closeButton);
        dialog.ShowDialog(this);
    }




    
    private async void DeployIISButton_Click(object sender, EventArgs e)
    {
        // 检测IIS服务是否安装
        if (!IsIISInstalled())
        {
            var result = MessageBox.Show(
                "检测到系统未安装Internet Information Services (IIS)服务。\n\n" +
                "IIS是部署Web应用程序的必需组件。\n\n" +
                "点击'是'自动安装IIS\n" +
                "点击'否'取消部署\n" +
                "点击'取消'手动安装后继续",
                "IIS服务未安装",
                MessageBoxButtons.YesNoCancel,
                MessageBoxIcon.Warning
            );
            
            if (result == DialogResult.Yes)
            {
                // 确认安装
                var confirmResult = MessageBox.Show(
                    "即将开始安装IIS服务，该过程可能需要几分钟时间。\n\n" +
                    "安装过程中请不要关闭程序。\n\n" +
                    "确认开始安装吗？",
                    "确认安装IIS",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question
                );
                
                if (confirmResult == DialogResult.Yes)
                {
                    // 检查管理员权限
                    if (!IsRunningAsAdministrator())
                    {
                        var adminResult = MessageBox.Show(
                            "安装IIS需要管理员权限。\n\n" +
                            "点击'是'以管理员身份重新启动程序\n" +
                            "点击'否'取消安装",
                            "需要管理员权限",
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Warning
                        );
                        
                        if (adminResult == DialogResult.Yes)
                        {
                            RestartAsAdmin();
                            return;
                        }
                        else
                        {
                            return;
                        }
                    }
                    
                    // 异步安装IIS
                    var installResult = await InstallIISAsync();
                    if (installResult)
                    {
                        LogMessage("IIS安装成功", Color.Green);
                    }
                    else
                    {
                        LogMessage("IIS安装失败，请手动安装", Color.Red);
                        return;
                    }
                }
                else
                {
                    return;
                }
            }
            else if (result == DialogResult.No)
            {
                return;
            }
            else // Cancel
            {
                LogMessage("警告: 请确保IIS已正确安装", Color.Orange);
            }
        }
        
        ShowDeployIISDialog();
    }
    
    private void ShowDeployIISDialog()
    {
        var dialog = new Form
        {
            Text = "部署IIS服务",
            Size = new Size(500, 350),
            StartPosition = FormStartPosition.CenterParent,
            FormBorderStyle = FormBorderStyle.FixedDialog,
            MaximizeBox = false,
            MinimizeBox = false
        };

        var siteNameLabel = new Label { Text = "站点名称:", Location = new Point(10, 20), Size = new Size(80, 20) };
        var siteNameTextBox = new TextBox { Location = new Point(100, 18), Size = new Size(350, 25) };
        
        var productLabel = new Label { Text = "产品:", Location = new Point(10, 55), Size = new Size(80, 20) };
        var productComboBox = new ComboBox { Location = new Point(100, 53), Size = new Size(200, 25), DropDownStyle = ComboBoxStyle.DropDownList };
        
        var versionLabel = new Label { Text = "版本:", Location = new Point(320, 55), Size = new Size(50, 20) };
        var versionComboBox = new ComboBox { Location = new Point(380, 53), Size = new Size(100, 25), DropDownStyle = ComboBoxStyle.DropDownList };
        
        var urlLabel = new Label { Text = "下载地址:", Location = new Point(10, 90), Size = new Size(80, 20) };
        var urlTextBox = new TextBox { Location = new Point(100, 88), Size = new Size(350, 25) };
        
        var targetLabel = new Label { Text = "部署路径:", Location = new Point(10, 125), Size = new Size(80, 20) };
        var targetTextBox = new TextBox { Location = new Point(100, 123), Size = new Size(300, 25) };
        var browseButton = new Button { Text = "浏览", Location = new Point(410, 123), Size = new Size(50, 25) };
        browseButton.Click += (s, e) =>
        {
            using var folderDialog = new FolderBrowserDialog();
            if (folderDialog.ShowDialog() == DialogResult.OK)
            {
                targetTextBox.Text = folderDialog.SelectedPath;
            }
        };
        
        var portLabel = new Label { Text = "端口:", Location = new Point(10, 160), Size = new Size(80, 20) };
        var portTextBox = new TextBox { Location = new Point(100, 158), Size = new Size(100, 25), Text = "80" };
        
        // 加载产品列表（只加载IIS类型的产品）
        LoadProductNamesAsync(productComboBox, "", "iis");
        
        // 产品选择变化时加载版本
        productComboBox.SelectedIndexChanged += async (s, e) =>
        {
            if (productComboBox.SelectedItem != null)
            {
                var versions = await updateManager.GetVersionsFromAPI(productComboBox.SelectedItem.ToString());
                versionComboBox.Items.Clear();
                foreach (var version in versions)
                {
                    versionComboBox.Items.Add(version);
                }
                if (versionComboBox.Items.Count > 0)
                {
                    versionComboBox.SelectedIndex = 0;
                    // 使用配置文件中的下载地址
                    urlTextBox.Text = updateManager.GetDownloadBaseUrl();
                }
            }
        };
        
        // 版本选择变化时更新下载地址
        versionComboBox.SelectedIndexChanged += (s, e) =>
        {
            if (productComboBox.SelectedItem != null && versionComboBox.SelectedItem != null)
            {
                // 使用配置文件中的下载地址
                urlTextBox.Text = updateManager.GetDownloadBaseUrl();
            }
        };
        
        var deployButton = new Button { Text = "部署", Location = new Point(300, 200), Size = new Size(70, 25) };
        var cancelButton = new Button { Text = "取消", Location = new Point(380, 200), Size = new Size(70, 25), DialogResult = DialogResult.Cancel };
        
        deployButton.Click += async (s, e) =>
        {
            if (string.IsNullOrWhiteSpace(siteNameTextBox.Text) || string.IsNullOrWhiteSpace(urlTextBox.Text) || string.IsNullOrWhiteSpace(targetTextBox.Text))
            {
                MessageBox.Show("请填写所有必需信息");
                return;
            }
            
            if (!int.TryParse(portTextBox.Text, out int port))
            {
                MessageBox.Show("请输入有效的端口号");
                return;
            }
            
            deployButton.Enabled = false;
            isTaskRunning = true;
            this.Enabled = false; // 禁用整个主窗体
            var progress = new Progress<string>(msg => LogMessage($"[部署] {msg}"));
            
            try
            {
                var success = await updateManager.DeployIISServiceFromUrl(siteNameTextBox.Text.Trim(), urlTextBox.Text.Trim(), targetTextBox.Text.Trim(), port, progress);
                
                if (success && productComboBox.SelectedItem != null && versionComboBox.SelectedItem != null)
            {
                // 自动添加到产品列表
                var product = new Product
                {
                    Id = $"iis_{Guid.NewGuid().ToString("N")[..8]}",
                    Name = siteNameTextBox.Text.Trim(),
                    Type = "iis",
                    Path = Path.Combine(targetTextBox.Text.Trim(), $"{siteNameTextBox.Text.Trim()}_{port}"),
                    SiteName = siteNameTextBox.Text.Trim(),
                    BackupPath = $"C:\\Backups\\{siteNameTextBox.Text.Trim()}",
                    CurrentVersion = versionComboBox.SelectedItem.ToString(),
                    ProductName = productComboBox.SelectedItem.ToString()
                };
                updateManager.AddProduct(product);
                LoadProducts();
                
                    LogMessage("部署成功并已添加到产品列表", Color.Green);
                    dialog.DialogResult = DialogResult.OK;
                }
                else if (!success)
                {
                    LogMessage("部署失败", Color.Red);
                    deployButton.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                LogMessage($"部署失败: {ex.Message}", Color.Red);
                MessageBox.Show($"部署失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                deployButton.Enabled = true;
                isTaskRunning = false;
                this.Enabled = true; // 重新启用主窗体
            }
        };
        
        dialog.FormClosing += (s, e) =>
        {
            if (isTaskRunning)
            {
                MessageBox.Show("当前有部署任务正在进行，无法关闭页面", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                e.Cancel = true;
            }
        };
        
        dialog.Controls.AddRange(new Control[] { siteNameLabel, siteNameTextBox, productLabel, productComboBox, versionLabel, versionComboBox, urlLabel, urlTextBox, targetLabel, targetTextBox, browseButton, portLabel, portTextBox, deployButton, cancelButton });
        dialog.ShowDialog(this);
    }
    
    private void DeployServiceButton_Click(object sender, EventArgs e)
    {
        ShowDeployServiceDialog();
    }
    
    private void ShowDeployServiceDialog()
    {
        var dialog = new Form
        {
            Text = "部署Windows服务",
            Size = new Size(500, 300),
            StartPosition = FormStartPosition.CenterParent,
            FormBorderStyle = FormBorderStyle.FixedDialog,
            MaximizeBox = false,
            MinimizeBox = false
        };

        var serviceNameLabel = new Label { Text = "服务名称:", Location = new Point(10, 20), Size = new Size(80, 20) };
        var serviceNameTextBox = new TextBox { Location = new Point(100, 18), Size = new Size(350, 25) };
        
        var productLabel = new Label { Text = "产品:", Location = new Point(10, 55), Size = new Size(80, 20) };
        var productComboBox = new ComboBox { Location = new Point(100, 53), Size = new Size(200, 25), DropDownStyle = ComboBoxStyle.DropDownList };
        
        var versionLabel = new Label { Text = "版本:", Location = new Point(320, 55), Size = new Size(50, 20) };
        var versionComboBox = new ComboBox { Location = new Point(380, 53), Size = new Size(100, 25), DropDownStyle = ComboBoxStyle.DropDownList };
        
        var urlLabel = new Label { Text = "下载地址:", Location = new Point(10, 90), Size = new Size(80, 20) };
        var urlTextBox = new TextBox { Location = new Point(100, 88), Size = new Size(350, 25) };
        
        var targetLabel = new Label { Text = "部署路径:", Location = new Point(10, 125), Size = new Size(80, 20) };
        var targetTextBox = new TextBox { Location = new Point(100, 123), Size = new Size(300, 25) };
        var browseButton = new Button { Text = "浏览", Location = new Point(410, 123), Size = new Size(50, 25) };
        browseButton.Click += (s, e) =>
        {
            using var folderDialog = new FolderBrowserDialog();
            if (folderDialog.ShowDialog() == DialogResult.OK)
            {
                targetTextBox.Text = folderDialog.SelectedPath;
            }
        };
        
        // 加载产品列表（只加载Windows服务类型的产品）
        LoadProductNamesAsync(productComboBox, "", "services");
        
        // 产品选择变化时加载版本
        productComboBox.SelectedIndexChanged += async (s, e) =>
        {
            if (productComboBox.SelectedItem != null)
            {
                var versions = await updateManager.GetVersionsFromAPI(productComboBox.SelectedItem.ToString());
                versionComboBox.Items.Clear();
                foreach (var version in versions)
                {
                    versionComboBox.Items.Add(version);
                }
                if (versionComboBox.Items.Count > 0)
                {
                    versionComboBox.SelectedIndex = 0;
                    urlTextBox.Text = updateManager.GetServiceDownloadUrl();
                }
            }
        };
        
        versionComboBox.SelectedIndexChanged += (s, e) =>
        {
            if (productComboBox.SelectedItem != null && versionComboBox.SelectedItem != null)
            {
                urlTextBox.Text = updateManager.GetServiceDownloadUrl();
            }
        };
        
        var deployButton = new Button { Text = "部署", Location = new Point(300, 160), Size = new Size(70, 25) };
        var cancelButton = new Button { Text = "取消", Location = new Point(380, 160), Size = new Size(70, 25), DialogResult = DialogResult.Cancel };
        
        deployButton.Click += async (s, e) =>
        {
            if (string.IsNullOrWhiteSpace(serviceNameTextBox.Text) || string.IsNullOrWhiteSpace(urlTextBox.Text) || string.IsNullOrWhiteSpace(targetTextBox.Text))
            {
                MessageBox.Show("请填写所有必需信息");
                return;
            }
            
            deployButton.Enabled = false;
            isTaskRunning = true;
            this.Enabled = false;
            var progress = new Progress<string>(msg => LogMessage($"[服务部署] {msg}"));
            
            try
            {
                var success = await updateManager.DeployWindowsServiceFromUrl(serviceNameTextBox.Text.Trim(), urlTextBox.Text.Trim(), targetTextBox.Text.Trim(), progress);
                
                if (success && productComboBox.SelectedItem != null && versionComboBox.SelectedItem != null)
                {
                    var product = new Product
                    {
                        Id = $"service_{Guid.NewGuid().ToString("N")[..8]}",
                        Name = serviceNameTextBox.Text.Trim(),
                        Type = "service",
                        Path = Path.Combine(targetTextBox.Text.Trim(), $"server{serviceNameTextBox.Text.Trim()}"),
                        ServiceName = serviceNameTextBox.Text.Trim(),
                        BackupPath = $"C:\\Backups\\{serviceNameTextBox.Text.Trim()}",
                        CurrentVersion = versionComboBox.SelectedItem.ToString(),
                        ProductName = productComboBox.SelectedItem.ToString()
                    };
                    updateManager.AddProduct(product);
                    LoadProducts();
                    
                    LogMessage("服务部署成功并已添加到产品列表", Color.Green);
                    dialog.DialogResult = DialogResult.OK;
                }
                else if (!success)
                {
                    LogMessage("服务部署失败", Color.Red);
                }
            }
            catch (Exception ex)
            {
                LogMessage($"服务部署失败: {ex.Message}", Color.Red);
                MessageBox.Show($"服务部署失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                deployButton.Enabled = true;
                isTaskRunning = false;
                this.Enabled = true;
            }
        };
        
        dialog.FormClosing += (s, e) =>
        {
            if (isTaskRunning)
            {
                MessageBox.Show("当前有部署任务正在进行，无法关闭页面", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                e.Cancel = true;
            }
        };
        
        dialog.Controls.AddRange(new Control[] { serviceNameLabel, serviceNameTextBox, productLabel, productComboBox, versionLabel, versionComboBox, urlLabel, urlTextBox, targetLabel, targetTextBox, browseButton, deployButton, cancelButton });
        dialog.ShowDialog(this);
    }
    
    private void DeleteProductButton_Click(object sender, EventArgs e)
    {
        var checkedItems = productListView.CheckedItems;
        if (checkedItems.Count == 0)
        {
            MessageBox.Show("请选中要删除的产品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }
        
        var result = MessageBox.Show($"确定要删除选中的 {checkedItems.Count} 个产品吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (result == DialogResult.Yes)
        {
            foreach (ListViewItem item in checkedItems)
            {
                var product = (Product)item.Tag;
                updateManager.DeleteProduct(product.Id);
                LogMessage($"已删除产品: {product.Name}", Color.Green);
            }
            LoadProducts();
        }
    }
    
    private void EditProductButton_Click(object sender, EventArgs e)
    {
        var selectedProduct = GetSelectedProduct();
        if (selectedProduct == null)
        {
            MessageBox.Show("请选择要修改的产品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }
        
        ShowEditProductDialog(selectedProduct);
    }
    
    private void ShowEditProductDialog(Product product)
    {
        var dialog = new Form
        {
            Text = $"修改产品 - {product.Name}",
            Size = new Size(350, 200),
            StartPosition = FormStartPosition.CenterParent,
            FormBorderStyle = FormBorderStyle.FixedDialog,
            MaximizeBox = false,
            MinimizeBox = false
        };

        var productNameLabel = new Label { Text = "所属产品:", Location = new Point(10, 20), Size = new Size(80, 20) };
        var productNameComboBox = new ComboBox { Location = new Point(100, 18), Size = new Size(200, 25), DropDownStyle = ComboBoxStyle.DropDownList };
        
        var versionLabel = new Label { Text = "当前版本:", Location = new Point(10, 55), Size = new Size(80, 20) };
        var versionTextBox = new TextBox { Location = new Point(100, 53), Size = new Size(200, 25), Text = product.CurrentVersion };
        
        var okButton = new Button { Text = "确定", Location = new Point(150, 90), Size = new Size(70, 25) };
        var cancelButton = new Button { Text = "取消", Location = new Point(230, 90), Size = new Size(70, 25), DialogResult = DialogResult.Cancel };
        
        // 加载产品列表
        LoadProductNamesAsync(productNameComboBox, product.ProductName);
        
        // 产品选择变化时自动获取版本
        productNameComboBox.SelectedIndexChanged += async (s, e) =>
        {
            if (productNameComboBox.SelectedItem != null)
            {
                var versions = await updateManager.GetVersionsFromAPI(productNameComboBox.SelectedItem.ToString());
                if (versions.Count > 0)
                {
                    versionTextBox.Text = versions[0]; // 设置为最新版本（API返回已按时间倒序）
                }
            }
        };
        
        okButton.Click += (s, e) =>
        {
            if (productNameComboBox.SelectedItem == null)
            {
                MessageBox.Show("请选择所属产品");
                return;
            }
            
            product.ProductName = productNameComboBox.SelectedItem.ToString();
            product.CurrentVersion = versionTextBox.Text.Trim();
            updateManager.UpdateProduct(product);
            LoadProducts();
            LogMessage($"已修改产品: {product.Name}", Color.Green);
            dialog.DialogResult = DialogResult.OK;
        };
        
        dialog.Controls.AddRange(new Control[] { productNameLabel, productNameComboBox, versionLabel, versionTextBox, okButton, cancelButton });
        dialog.ShowDialog(this);
    }
    
    private async void SyncToServerButton_Click(object sender, EventArgs e)
    {
        var selectedProduct = GetSelectedProduct();
        if (selectedProduct == null)
        {
            MessageBox.Show("请选择要同步的产品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }
        
        try
        {
            var success = await updateManager.SyncProductToServer(selectedProduct);
            if (success)
            {
                LogMessage($"产品 {selectedProduct.Name} 同步成功", Color.Green);
            }
            else
            {
                LogMessage($"产品 {selectedProduct.Name} 同步失败", Color.Red);
            }
        }
        catch (Exception ex)
        {
            LogMessage($"同步失败: {ex.Message}", Color.Red);
        }
    }
    
    private async void CheckUpdateButton_Click(object sender, EventArgs e)
    {
        try
        {
            SetUIEnabled(false);
            progressBar.Visible = true;
            statusLabel.Text = "正在检测更新...";
            
            var currentVersion = GetCurrentVersion();
            var lastUpdateVersion = updateManager.GetLastUpdateVersion();
            var latestVersion = await updateManager.GetLatestVersion("AutoUpdater");
            
            if (string.IsNullOrEmpty(latestVersion))
            {
                LogMessage("无法获取最新版本信息", Color.Red);
                return;
            }
            
            // 检查是否已经更新过该版本
            if (!string.IsNullOrEmpty(lastUpdateVersion) && lastUpdateVersion == latestVersion)
            {
                LogMessage($"当前已是最新版本: {latestVersion}", Color.Green);
                MessageBox.Show($"当前已是最新版本: {latestVersion}", "检测结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            
            if (IsNewerVersion(latestVersion, currentVersion))
            {
                var result = MessageBox.Show($"发现新版本 {latestVersion}，当前版本 {currentVersion}，是否立即更新？", "更新提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                
                if (result == DialogResult.Yes)
                {
                    await UpdateSelf(latestVersion);
                }
            }
            else
            {
                LogMessage($"当前已是最新版本: {currentVersion}", Color.Green);
                MessageBox.Show($"当前已是最新版本: {currentVersion}", "检测结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        catch (Exception ex)
        {
            Logger.LogError("检测更新失败", ex);
            LogMessage($"检测更新失败: {ex.Message}", Color.Red);
        }
        finally
        {
            progressBar.Visible = false;
            statusLabel.Text = "就绪";
            SetUIEnabled(true);
        }
    }
    
    private string GetCurrentVersion()
    {
        var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
        return version?.ToString(3) ?? "1.0.0";
    }
    
    private bool IsNewerVersion(string latestVersion, string currentVersion)
    {
        try
        {
            var latest = new Version(latestVersion);
            var current = new Version(currentVersion);
            return latest > current;
        }
        catch
        {
            return false;
        }
    }
    
    private async Task UpdateSelf(string newVersion)
    {
        try
        {
            LogMessage($"开始更新AutoUpdater到版本 {newVersion}");
            statusLabel.Text = "正在更新AutoUpdater...";
            
            var progress = new Progress<string>(message => LogMessage($"[AutoUpdater更新] {message}"));
            
            var success = await updateManager.UpdateAutoUpdater(newVersion, progress);
            
            if (success)
            {
                LogMessage("AutoUpdater更新成功，程序将重启", Color.Green);
                MessageBox.Show("AutoUpdater更新成功，程序将重启", "更新成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                
                // 重启程序
                System.Diagnostics.Process.Start(Application.ExecutablePath);
                Environment.Exit(0);
            }
            else
            {
                LogMessage("AutoUpdater更新失败", Color.Red);
            }
        }
        catch (Exception ex)
        {
            Logger.LogError("AutoUpdater更新失败", ex);
            LogMessage($"AutoUpdater更新失败: {ex.Message}", Color.Red);
        }
    }

    private async void LoadProductNamesAsync(ComboBox comboBox, string selectedProduct = "", string deployType = "")
    {
        try
        {
            var products = await updateManager.GetProductsFromAPI(deployType);
            if (InvokeRequired)
            {
                Invoke(() =>
                {
                    comboBox.Items.Clear();
                    comboBox.Items.AddRange(products.ToArray());
                    
                    if (!string.IsNullOrEmpty(selectedProduct))
                    {
                        var index = comboBox.Items.IndexOf(selectedProduct);
                        if (index >= 0) comboBox.SelectedIndex = index;
                    }
                    else if (comboBox.Items.Count > 0)
                    {
                        comboBox.SelectedIndex = 0;
                    }
                });
            }
            else
            {
                comboBox.Items.Clear();
                comboBox.Items.AddRange(products.ToArray());
                
                if (!string.IsNullOrEmpty(selectedProduct))
                {
                    var index = comboBox.Items.IndexOf(selectedProduct);
                    if (index >= 0) comboBox.SelectedIndex = index;
                }
                else if (comboBox.Items.Count > 0)
                {
                    comboBox.SelectedIndex = 0;
                }
            }
        }
        catch (Exception ex)
        {
            Logger.LogError("加载产品列表失败", ex);
            LogMessage($"加载产品列表失败: {ex.Message}", Color.Red);
        }
    }
    

    
    private void ShowRemoteManageDialog()
    {
        var dialog = new Form
        {
            Text = "远程机器管理",
            Size = new Size(800, 600),
            StartPosition = FormStartPosition.CenterParent,
            FormBorderStyle = FormBorderStyle.Sizable
        };

        var machineListView = new ListView
        {
            Location = new Point(10, 40),
            Size = new Size(760, 200),
            View = View.Details,
            FullRowSelect = true,
            GridLines = true,
            CheckBoxes = true
        };
        machineListView.Columns.Add("机器名称", 120);
        machineListView.Columns.Add("IP地址", 120);
        machineListView.Columns.Add("端口", 60);
        machineListView.Columns.Add("用户名", 100);
        machineListView.Columns.Add("状态", 80);
        machineListView.Columns.Add("备注", 200);
        
        // 加载已保存的远程机器
        LoadRemoteMachines(machineListView);
        
        var addButton = new Button { Text = "添加机器", Location = new Point(10, 10), Size = new Size(80, 25) };
        addButton.Click += (s, e) => ShowAddMachineDialog(machineListView);
        
        var editButton = new Button { Text = "编辑机器", Location = new Point(100, 10), Size = new Size(80, 25) };
        editButton.Click += (s, e) => EditSelectedMachine(machineListView);
        
        var deleteButton = new Button { Text = "删除机器", Location = new Point(190, 10), Size = new Size(80, 25) };
        deleteButton.Click += (s, e) => DeleteSelectedMachines(machineListView);
        
        var testButton = new Button { Text = "测试连接", Location = new Point(280, 10), Size = new Size(80, 25) };
        testButton.Click += async (s, e) => await TestSelectedMachines(machineListView);
        
        var remoteUpdateButton = new Button { Text = "远程更新", Location = new Point(370, 10), Size = new Size(80, 25) };
        remoteUpdateButton.Click += async (s, e) => await TestSelectedMachines(machineListView);
        
        var closeButton = new Button { Text = "关闭", Location = new Point(700, 560), Size = new Size(70, 25), DialogResult = DialogResult.OK };
        
        dialog.Controls.AddRange(new Control[] { addButton, editButton, deleteButton, testButton, remoteUpdateButton, machineListView, closeButton });
        dialog.ShowDialog(this);
    }
    
    private void LoadRemoteMachines(ListView listView)
    {
        listView.Items.Clear();
        var machines = updateManager.GetRemoteMachines();
        
        foreach (var machine in machines)
        {
            var item = new ListViewItem(machine.Name);
            item.SubItems.Add(machine.IPAddress);
            item.SubItems.Add(machine.Port.ToString());
            item.SubItems.Add(machine.Username);
            item.SubItems.Add(machine.IsOnline ? "在线" : "离线");
            item.SubItems.Add(machine.Description);
            item.Tag = machine;
            item.ForeColor = machine.IsOnline ? Color.Black : Color.Gray;
            listView.Items.Add(item);
        }
    }
    
    private void ShowAddMachineDialog(ListView listView)
    {
        var dialog = new Form
        {
            Text = "添加远程机器",
            Size = new Size(400, 300),
            StartPosition = FormStartPosition.CenterParent,
            FormBorderStyle = FormBorderStyle.FixedDialog
        };
        
        var nameLabel = new Label { Text = "机器名称:", Location = new Point(10, 20), Size = new Size(80, 20) };
        var nameTextBox = new TextBox { Location = new Point(100, 18), Size = new Size(250, 25) };
        
        var ipLabel = new Label { Text = "IP地址:", Location = new Point(10, 55), Size = new Size(80, 20) };
        var ipTextBox = new TextBox { Location = new Point(100, 53), Size = new Size(250, 25) };
        
        var portLabel = new Label { Text = "端口:", Location = new Point(10, 90), Size = new Size(80, 20) };
        var portTextBox = new TextBox { Location = new Point(100, 88), Size = new Size(100, 25), Text = "8080" };
        
        var userLabel = new Label { Text = "用户名:", Location = new Point(10, 125), Size = new Size(80, 20) };
        var userTextBox = new TextBox { Location = new Point(100, 123), Size = new Size(250, 25) };
        
        var passLabel = new Label { Text = "密码:", Location = new Point(10, 160), Size = new Size(80, 20) };
        var passTextBox = new TextBox { Location = new Point(100, 158), Size = new Size(250, 25), UseSystemPasswordChar = true };
        
        var descLabel = new Label { Text = "备注:", Location = new Point(10, 195), Size = new Size(80, 20) };
        var descTextBox = new TextBox { Location = new Point(100, 193), Size = new Size(250, 25) };
        
        var okButton = new Button { Text = "确定", Location = new Point(200, 230), Size = new Size(70, 25) };
        var cancelButton = new Button { Text = "取消", Location = new Point(280, 230), Size = new Size(70, 25), DialogResult = DialogResult.Cancel };
        
        okButton.Click += (s, e) =>
        {
            if (string.IsNullOrWhiteSpace(nameTextBox.Text) || string.IsNullOrWhiteSpace(ipTextBox.Text))
            {
                MessageBox.Show("请填写机器名称和IP地址");
                return;
            }
            
            if (!int.TryParse(portTextBox.Text, out int port))
            {
                MessageBox.Show("请输入有效的端口号");
                return;
            }
            
            var machine = new RemoteMachine
            {
                Id = Guid.NewGuid().ToString(),
                Name = nameTextBox.Text.Trim(),
                IPAddress = ipTextBox.Text.Trim(),
                Port = port,
                Username = userTextBox.Text.Trim(),
                Password = passTextBox.Text,
                Description = descTextBox.Text.Trim()
            };
            
            updateManager.AddRemoteMachine(machine);
            LoadRemoteMachines(listView);
            LogMessage($"已添加远程机器: {machine.Name} ({machine.IPAddress})", Color.Green);
            dialog.DialogResult = DialogResult.OK;
        };
        
        dialog.Controls.AddRange(new Control[] { nameLabel, nameTextBox, ipLabel, ipTextBox, portLabel, portTextBox, userLabel, userTextBox, passLabel, passTextBox, descLabel, descTextBox, okButton, cancelButton });
        dialog.ShowDialog();
    }
    
    private void EditSelectedMachine(ListView listView)
    {
        if (listView.SelectedItems.Count == 0)
        {
            MessageBox.Show("请选择要编辑的机器");
            return;
        }
        
        var machine = (RemoteMachine)listView.SelectedItems[0].Tag;
        // 类似添加机器的对话框，但预填充数据
        // 简化实现，直接复用添加逻辑
    }
    
    private void DeleteSelectedMachines(ListView listView)
    {
        var checkedItems = listView.CheckedItems;
        if (checkedItems.Count == 0)
        {
            MessageBox.Show("请选中要删除的机器");
            return;
        }
        
        var result = MessageBox.Show($"确定要删除选中的 {checkedItems.Count} 台机器吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (result == DialogResult.Yes)
        {
            foreach (ListViewItem item in checkedItems)
            {
                var machine = (RemoteMachine)item.Tag;
                updateManager.DeleteRemoteMachine(machine.Id);
                LogMessage($"已删除远程机器: {machine.Name}", Color.Green);
            }
            LoadRemoteMachines(listView);
        }
    }
    
    private async Task TestSelectedMachines(ListView listView)
    {
        var checkedItems = listView.CheckedItems;
        if (checkedItems.Count == 0)
        {
            MessageBox.Show("请选中要测试的机器");
            return;
        }
        
        LogMessage($"开始测试 {checkedItems.Count} 台远程机器连接...", Color.Blue);
        
        foreach (ListViewItem item in checkedItems)
        {
            var machine = (RemoteMachine)item.Tag;
            try
            {
                LogMessage($"[{machine.Name}] 正在测试连接到 {machine.IPAddress}:{machine.Port}...", Color.Blue);
                
                var isOnline = await updateManager.TestRemoteMachineConnection(machine);
                machine.IsOnline = isOnline;
                updateManager.UpdateRemoteMachine(machine);
                
                item.SubItems[4].Text = isOnline ? "在线" : "离线";
                item.ForeColor = isOnline ? Color.Black : Color.Gray;
                
                LogMessage($"[{machine.Name}] 连接测试: {(isOnline ? "成功" : "失败")}", isOnline ? Color.Green : Color.Red);
                
                if (!isOnline)
                {
                    LogMessage($"[{machine.Name}] 请检查: 1.网络连接 2.防火墙设置 3.IP地址是否正确", Color.Orange);
                }
            }
            catch (Exception ex)
            {
                LogMessage($"[{machine.Name}] 测试异常: {ex.Message}", Color.Red);
                item.SubItems[4].Text = "错误";
                item.ForeColor = Color.Red;
            }
        }
        
        LogMessage("远程机器连接测试完成", Color.Blue);
    }
    
    private void ShowRemoteDesktopDialog()
    {
        var dialog = new Form
        {
            Text = "远程桌面连接管理",
            Size = new Size(900, 700),
            StartPosition = FormStartPosition.CenterParent,
            FormBorderStyle = FormBorderStyle.Sizable
        };

        // 远程主机连接区域
        var connectionGroupBox = new GroupBox
        {
            Text = "远程主机连接",
            Location = new Point(10, 10),
            Size = new Size(860, 120)
        };

        var ipLabel = new Label { Text = "IP地址:", Location = new Point(10, 25), Size = new Size(60, 20) };
        var ipTextBox = new TextBox { Location = new Point(80, 23), Size = new Size(120, 25) };
        
        var portLabel = new Label { Text = "端口:", Location = new Point(210, 25), Size = new Size(40, 20) };
        var portTextBox = new TextBox { Location = new Point(260, 23), Size = new Size(60, 25), Text = "3389" };
        
        var userLabel = new Label { Text = "用户名:", Location = new Point(330, 25), Size = new Size(60, 20) };
        var userTextBox = new TextBox { Location = new Point(400, 23), Size = new Size(100, 25) };
        
        var passLabel = new Label { Text = "密码:", Location = new Point(510, 25), Size = new Size(40, 20) };
        var passTextBox = new TextBox { Location = new Point(560, 23), Size = new Size(100, 25), UseSystemPasswordChar = true };
        
        var connectButton = new Button { Text = "连接并加载IIS", Location = new Point(680, 23), Size = new Size(100, 25) };
        
        var nameLabel = new Label { Text = "主机名:", Location = new Point(10, 60), Size = new Size(60, 20) };
        var nameTextBox = new TextBox { Location = new Point(80, 58), Size = new Size(120, 25) };
        
        var statusLabel = new Label { Text = "状态: 未连接", Location = new Point(210, 60), Size = new Size(200, 20), ForeColor = Color.Gray };
        
        var saveButton = new Button { Text = "保存配置", Location = new Point(680, 58), Size = new Size(100, 25) };
        
        connectionGroupBox.Controls.AddRange(new Control[] { 
            ipLabel, ipTextBox, portLabel, portTextBox, userLabel, userTextBox, 
            passLabel, passTextBox, connectButton, nameLabel, nameTextBox, statusLabel, saveButton 
        });

        // IIS服务列表区域
        var iisGroupBox = new GroupBox
        {
            Text = "远程主机IIS服务列表",
            Location = new Point(10, 140),
            Size = new Size(860, 350)
        };

        var iisListView = new ListView
        {
            Location = new Point(10, 25),
            Size = new Size(840, 280),
            View = View.Details,
            FullRowSelect = true,
            GridLines = true,
            CheckBoxes = true
        };
        iisListView.Columns.Add("站点名称", 120);
        iisListView.Columns.Add("端口", 60);
        iisListView.Columns.Add("状态", 80);
        iisListView.Columns.Add("当前版本", 100);
        iisListView.Columns.Add("物理路径", 200);
        iisListView.Columns.Add("绑定信息", 200);
        iisListView.Columns.Add("主机", 100);

        var refreshIISButton = new Button { Text = "刷新IIS列表", Location = new Point(10, 315), Size = new Size(100, 25) };
        var selectAllButton = new Button { Text = "全选", Location = new Point(120, 315), Size = new Size(60, 25) };
        var selectNoneButton = new Button { Text = "全不选", Location = new Point(190, 315), Size = new Size(60, 25) };
        
        iisGroupBox.Controls.AddRange(new Control[] { iisListView, refreshIISButton, selectAllButton, selectNoneButton });

        // 版本选择和更新区域
        var updateGroupBox = new GroupBox
        {
            Text = "版本选择和更新",
            Location = new Point(10, 500),
            Size = new Size(860, 120)
        };

        var productLabel = new Label { Text = "产品:", Location = new Point(10, 25), Size = new Size(50, 20) };
        var productComboBox = new ComboBox { Location = new Point(70, 23), Size = new Size(150, 25), DropDownStyle = ComboBoxStyle.DropDownList };
        
        var versionLabel = new Label { Text = "目标版本:", Location = new Point(230, 25), Size = new Size(70, 20) };
        var versionComboBox = new ComboBox { Location = new Point(310, 23), Size = new Size(120, 25), DropDownStyle = ComboBoxStyle.DropDownList };
        
        var updateSelectedButton = new Button { Text = "更新选中服务", Location = new Point(450, 23), Size = new Size(100, 25) };
        var batchUpdateButton = new Button { Text = "批量更新", Location = new Point(560, 23), Size = new Size(80, 25) };
        
        var progressBar = new ProgressBar { Location = new Point(10, 60), Size = new Size(630, 20), Visible = false };
        var progressLabel = new Label { Text = "就绪", Location = new Point(10, 90), Size = new Size(630, 20), ForeColor = Color.Blue };
        
        updateGroupBox.Controls.AddRange(new Control[] { 
            productLabel, productComboBox, versionLabel, versionComboBox, 
            updateSelectedButton, batchUpdateButton, progressBar, progressLabel 
        });

        var closeButton = new Button { Text = "关闭", Location = new Point(800, 630), Size = new Size(70, 25), DialogResult = DialogResult.OK };

        dialog.Controls.AddRange(new Control[] { connectionGroupBox, iisGroupBox, updateGroupBox, closeButton });

        // 远程桌面管理器
        var rdpManager = new RemoteDesktopManager();
        RemoteConnectionResult? currentConnection = null;

        // 连接按钮事件
        connectButton.Click += async (s, e) =>
        {
            if (string.IsNullOrWhiteSpace(ipTextBox.Text) || string.IsNullOrWhiteSpace(userTextBox.Text))
            {
                MessageBox.Show("请填写IP地址和用户名");
                return;
            }

            var machine = new RemoteMachine
            {
                Name = string.IsNullOrWhiteSpace(nameTextBox.Text) ? ipTextBox.Text : nameTextBox.Text,
                IPAddress = ipTextBox.Text.Trim(),
                Port = int.TryParse(portTextBox.Text, out int port) ? port : 3389,
                Username = userTextBox.Text.Trim(),
                Password = passTextBox.Text
            };

            connectButton.Enabled = false;
            statusLabel.Text = "状态: 正在连接...";
            statusLabel.ForeColor = Color.Blue;
            
            var progress = new Progress<string>(message => 
            {
                LogMessage($"[远程连接] {message}");
                progressLabel.Text = message;
            });

            try
            {
                currentConnection = await rdpManager.ConnectAndLoadIISServices(machine, progress);
                
                if (currentConnection.IsConnected)
                {
                    statusLabel.Text = $"状态: 已连接 ({currentConnection.IISServices.Count} 个IIS服务)";
                    statusLabel.ForeColor = Color.Green;
                    
                    // 加载IIS服务到列表
                    LoadRemoteIISServices(iisListView, currentConnection.IISServices);
                    
                    LogMessage($"成功连接到 {machine.Name}，发现 {currentConnection.IISServices.Count} 个IIS服务", Color.Green);
                }
                else
                {
                    statusLabel.Text = $"状态: 连接失败 - {currentConnection.ErrorMessage}";
                    statusLabel.ForeColor = Color.Red;
                    LogMessage($"连接失败: {currentConnection.ErrorMessage}", Color.Red);
                }
            }
            catch (Exception ex)
            {
                statusLabel.Text = $"状态: 连接异常 - {ex.Message}";
                statusLabel.ForeColor = Color.Red;
                LogMessage($"连接异常: {ex.Message}", Color.Red);
            }
            finally
            {
                connectButton.Enabled = true;
                progressLabel.Text = "就绪";
            }
        };

        // 刷新IIS列表
        refreshIISButton.Click += async (s, e) =>
        {
            if (currentConnection?.IsConnected == true)
            {
                refreshIISButton.Enabled = false;
                var progress = new Progress<string>(message => progressLabel.Text = message);
                
                try
                {
                    var newConnection = await rdpManager.ConnectAndLoadIISServices(currentConnection.Machine, progress);
                    if (newConnection.IsConnected)
                    {
                        currentConnection = newConnection;
                        LoadRemoteIISServices(iisListView, currentConnection.IISServices);
                        LogMessage($"刷新完成，发现 {currentConnection.IISServices.Count} 个IIS服务", Color.Green);
                    }
                }
                finally
                {
                    refreshIISButton.Enabled = true;
                    progressLabel.Text = "就绪";
                }
            }
            else
            {
                MessageBox.Show("请先连接到远程主机");
            }
        };

        // 全选/全不选
        selectAllButton.Click += (s, e) =>
        {
            foreach (ListViewItem item in iisListView.Items)
                item.Checked = true;
        };
        
        selectNoneButton.Click += (s, e) =>
        {
            foreach (ListViewItem item in iisListView.Items)
                item.Checked = false;
        };

        // 加载产品列表
        LoadProductNamesAsync(productComboBox);
        
        // 产品选择变化时加载版本
        productComboBox.SelectedIndexChanged += async (s, e) =>
        {
            if (productComboBox.SelectedItem != null)
            {
                var versions = await updateManager.GetVersionsFromAPI(productComboBox.SelectedItem.ToString());
                versionComboBox.Items.Clear();
                foreach (var version in versions)
                {
                    versionComboBox.Items.Add(version);
                }
                if (versionComboBox.Items.Count > 0)
                {
                    versionComboBox.SelectedIndex = 0;
                }
            }
        };

        // 更新选中服务
        updateSelectedButton.Click += async (s, e) =>
        {
            await UpdateSelectedRemoteServices(iisListView, productComboBox, versionComboBox, rdpManager, currentConnection, progressBar, progressLabel);
        };

        // 批量更新
        batchUpdateButton.Click += async (s, e) =>
        {
            await BatchUpdateRemoteServices(iisListView, productComboBox, versionComboBox, rdpManager, currentConnection, progressBar, progressLabel);
        };

        // 保存配置
        saveButton.Click += (s, e) =>
        {
            if (string.IsNullOrWhiteSpace(ipTextBox.Text) || string.IsNullOrWhiteSpace(userTextBox.Text))
            {
                MessageBox.Show("请填写完整的连接信息");
                return;
            }

            var machine = new RemoteMachine
            {
                Id = Guid.NewGuid().ToString(),
                Name = string.IsNullOrWhiteSpace(nameTextBox.Text) ? ipTextBox.Text : nameTextBox.Text,
                IPAddress = ipTextBox.Text.Trim(),
                Port = int.TryParse(portTextBox.Text, out int port) ? port : 3389,
                Username = userTextBox.Text.Trim(),
                Password = passTextBox.Text,
                Description = "远程桌面连接"
            };

            updateManager.AddRemoteMachine(machine);
            LogMessage($"已保存远程主机配置: {machine.Name}", Color.Green);
            MessageBox.Show("远程主机配置已保存", "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
        };

        dialog.ShowDialog(this);
    }

    private void LoadRemoteIISServices(ListView listView, List<RemoteIISService> services)
    {
        listView.Items.Clear();
        
        foreach (var service in services)
        {
            var item = new ListViewItem(service.SiteName);
            item.SubItems.Add(service.Port.ToString());
            item.SubItems.Add(service.State);
            item.SubItems.Add(service.CurrentVersion);
            item.SubItems.Add(service.PhysicalPath);
            item.SubItems.Add(service.Bindings);
            item.SubItems.Add(service.MachineName);
            item.Tag = service;
            
            // 根据状态设置颜色
            if (service.State.ToLower().Contains("start"))
                item.ForeColor = Color.Green;
            else if (service.State.ToLower().Contains("stop"))
                item.ForeColor = Color.Red;
            else
                item.ForeColor = Color.Orange;
                
            listView.Items.Add(item);
        }
    }

    private async Task UpdateSelectedRemoteServices(ListView listView, ComboBox productComboBox, ComboBox versionComboBox, 
        RemoteDesktopManager rdpManager, RemoteConnectionResult? connection, ProgressBar progressBar, Label progressLabel)
    {
        var checkedServices = new List<RemoteIISService>();
        foreach (ListViewItem item in listView.CheckedItems)
        {
            checkedServices.Add((RemoteIISService)item.Tag);
        }

        if (checkedServices.Count == 0)
        {
            MessageBox.Show("请选择要更新的IIS服务");
            return;
        }

        if (productComboBox.SelectedItem == null || versionComboBox.SelectedItem == null)
        {
            MessageBox.Show("请选择产品和目标版本");
            return;
        }

        if (connection?.IsConnected != true)
        {
            MessageBox.Show("请先连接到远程主机");
            return;
        }

        var targetVersion = versionComboBox.SelectedItem.ToString();
        var result = MessageBox.Show($"确定要更新选中的 {checkedServices.Count} 个IIS服务到版本 {targetVersion} 吗？", 
            "确认更新", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        
        if (result != DialogResult.Yes)
            return;

        progressBar.Visible = true;
        progressBar.Style = ProgressBarStyle.Blocks;
        progressBar.Maximum = checkedServices.Count;
        progressBar.Value = 0;

        int successCount = 0;
        int failCount = 0;

        for (int i = 0; i < checkedServices.Count; i++)
        {
            var service = checkedServices[i];
            progressBar.Value = i;
            progressLabel.Text = $"正在更新 {service.SiteName} ({i + 1}/{checkedServices.Count})...";
            
            var progress = new Progress<string>(message => 
            {
                LogMessage($"[{service.SiteName}] {message}");
                progressLabel.Text = message;
            });

            try
            {
                var productName = productComboBox.SelectedItem.ToString();
                var success = await rdpManager.RemoteUpdateIISService(connection.Machine, service, productName, targetVersion, progress);
                
                if (success)
                {
                    successCount++;
                    LogMessage($"[{service.SiteName}] 远程更新成功", Color.Green);
                    
                    // 更新列表中的版本信息
                    var listItem = listView.Items.Cast<ListViewItem>().FirstOrDefault(item => item.Tag == service);
                    if (listItem != null)
                    {
                        listItem.SubItems[3].Text = targetVersion;
                    }
                }
                else
                {
                    failCount++;
                    LogMessage($"[{service.SiteName}] 远程更新失败", Color.Red);
                }
            }
            catch (Exception ex)
            {
                failCount++;
                LogMessage($"[{service.SiteName}] 远程更新异常: {ex.Message}", Color.Red);
            }

            Application.DoEvents();
        }

        progressBar.Value = checkedServices.Count;
        progressLabel.Text = "远程更新完成";
        
        LogMessage($"远程更新完成：成功 {successCount} 个，失败 {failCount} 个", successCount > 0 ? Color.Green : Color.Red);
        MessageBox.Show($"远程更新完成！\n\n成功: {successCount} 个\n失败: {failCount} 个", "更新结果", MessageBoxButtons.OK, MessageBoxIcon.Information);

        progressBar.Visible = false;
        progressLabel.Text = "就绪";
    }

    private async Task BatchUpdateRemoteServices(ListView listView, ComboBox productComboBox, ComboBox versionComboBox, 
        RemoteDesktopManager rdpManager, RemoteConnectionResult? connection, ProgressBar progressBar, Label progressLabel)
    {
        // 批量更新所有服务
        foreach (ListViewItem item in listView.Items)
        {
            item.Checked = true;
        }
        
        await UpdateSelectedRemoteServices(listView, productComboBox, versionComboBox, rdpManager, connection, progressBar, progressLabel);
    }
}